package com.szgd.service.weixin;

import com.szgd.bean.Remind;
import com.szgd.bean.SysDict;
import com.szgd.bean.User;
import com.szgd.dao.ecdata.weixin.WeChatMapper;
import com.szgd.service.elseData.PitService;
import com.szgd.service.elseData.TunnelService;
import com.szgd.service.personnel.AttachService;
import com.szgd.service.personnel.EnterExitService;
import com.szgd.service.personnel.PersonnelInfoService;
import com.szgd.service.personnel.RemindService;
import com.szgd.service.project.BidService;
import com.szgd.service.project.SiteService;
import com.szgd.service.schedule.AccessorStructureScheduleService;
import com.szgd.service.schedule.MainWorkScheduleService;
import com.szgd.service.schedule.TunnellingWorkScheduleService;
import com.szgd.service.sys.SimulateBaseService;
import com.szgd.service.sys.SysDictService;
import com.szgd.service.sys.UserService;
import com.szgd.util.FileUtil;
import com.szgd.util.PropertiesUtil;
import com.szgd.util.SysUtil;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class WeChatService extends SimulateBaseService {
    @Autowired
    WeChatMapper weChatMapper;
    @Autowired
    BidService bidService;
    @Autowired
    SiteService siteService;
    @Autowired
    SysDictService sysDictService;
    @Autowired
    PersonnelInfoService personnelInfoService;
    @Autowired
    UserService userService;
    @Autowired
    MainWorkScheduleService mainWorkScheduleService;
    @Autowired
    TunnellingWorkScheduleService tunnellingWorkScheduleService;
    @Autowired
    AccessorStructureScheduleService accessorStructureScheduleService;
    @Autowired
    EnterExitService enterExitService;
    @Autowired
    RemindService remindService;
    @Autowired
    PitService pitService;
    @Autowired
    TunnelService tunnelService;
    @Autowired
    AttachService attachService;

    public Map<String, Object> getBidAndSiteAndRP(){
        Map<String, Object> res = new HashMap<>();
        List<String> bid = new ArrayList<>();//标段
        List<List<String>> site = new ArrayList<>();//存放站点名称
        List<List<Long>> siteId = new ArrayList<>();//存放站点id
        List<Map<String, Object>> bidList = bidService.getBidListNoPage(null);
        for(int i = 0; i < bidList.size(); i++){
            bid.add(bidList.get(i).get("name").toString());
            Long bidId = Long.valueOf(bidList.get(i).get("id").toString());
            Map<String, Object> siteParam = new HashMap<>();
            siteParam.put("bidId",bidId);
            List<Map<String, Object>> siteList = siteService.getSiteListNoPage(siteParam);
            List<String> siteTemp = new ArrayList<>();
            List<Long> siteIdTemp = new ArrayList<>();
            for(int j = 0; j < siteList.size(); j++){
                siteTemp.add(siteList.get(j).get("name").toString());
                siteIdTemp.add(Long.valueOf(siteList.get(j).get("id").toString()));
            }
            site.add(siteTemp);
            siteId.add(siteIdTemp);
        }
        res.put("bid",bid);//标段名称
        res.put("site",site);//站点名称
        res.put("siteId",siteId);//站点id

        List<User> rpList = userService.getAllRpPerson();
        res.put("rpList",rpList);//获取所有上报人
        return res;
    }

    public Map<String, Object> getUserInfo(Map<String, Object> params){
        return weChatMapper.getUserInfo(params);
    }

    public List<Map<String,Object>> login(Map<String,Object> params){
        return weChatMapper.login(params);
    }

    public void updateOpenId(Map<String,Object> params){
        weChatMapper.updateOpenId(params);
    }

    public long getPersonBySiteId(Map<String,Object> params){
        return weChatMapper.getPersonBySiteId(params);
    }

    public Map<String, Object> getTotalChart(Map<String,Object> params) {
        DecimalFormat df = new DecimalFormat("0.#");
        Map<String, Object> res = new HashMap<>();
        List<Map<String,Object>> categoryOneArray = new ArrayList<>();
        List<Map<String, Object>> dataList = weChatMapper.totalCompleteRateAvg(params);
        for(int i = 0 ; i < dataList.size(); i++){
            Map<String, Object> categoryOneArrayItem = new HashMap<>();
            Map<String, Object> tempMap = dataList.get(i);
            Double whjg = tempMap.get("WHJG")==null?0.0:Double.valueOf(tempMap.get("WHJG").toString());
            Double tfkw = tempMap.get("TFKW")==null?0.0:Double.valueOf(tempMap.get("TFKW").toString());
            Double ztjg = tempMap.get("ZTJG")==null?0.0:Double.valueOf(tempMap.get("ZTJG").toString());
            Double tunnel = tempMap.get("TUNNEL")==null?0.0:Double.valueOf(tempMap.get("TUNNEL").toString());
            Double accessor = tempMap.get("ACCESSOR")==null?0.0:Double.valueOf(tempMap.get("ACCESSOR").toString());
            tempMap.put("WHJG",df.format(whjg));
            tempMap.put("TFKW",df.format(tfkw));
            tempMap.put("ZTJG",df.format(ztjg));
            tempMap.put("TUNNEL",df.format(tunnel));
            tempMap.put("ACCESSOR",df.format(accessor));
            categoryOneArrayItem.put("categoryTwoArray",tempMap);
            categoryOneArrayItem.put("name",tempMap.get("siteName"));
            categoryOneArray.add(categoryOneArrayItem);
        }
        res.put("categoryOneArray",categoryOneArray);
        return res;
    }

    //***************--APP--上传照片********************//
    public String uploadPic(HttpServletRequest request){
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        String picName = "";
        if(isMultipart) {
            MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
            MultipartFile multipartFile = req.getFile("file");
            if(multipartFile != null){
                String realPath = PropertiesUtil.get("uploadPath");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                String nowTime = sdf.format(new Date());
                //裁剪用户id
                String originalFirstName = multipartFile.getOriginalFilename();
                String picFirstName = originalFirstName.substring(0, originalFirstName.indexOf("."));
                //取得图片的格式后缀
                String originalLastName = multipartFile.getOriginalFilename();
                String picLastName = originalLastName.substring(originalLastName.lastIndexOf("."));
                //拼接：名字+时间戳+后缀
                picName = picFirstName + "-" + nowTime + picLastName;
                try {
                    File dir = new File(realPath);
                    //如果文件目录不存在，创建文件目录
                    if (!dir.exists()) {
                        dir.mkdirs();
                        System.out.println("创建文件目录成功：" + realPath);
                    }
                    String subPath = FileUtil.createSubFolder(dir.getPath(),SysUtil.getDateStr(null,"yyyyMM"));
                    File file = new File(realPath + File.separator + subPath, picName);
                    multipartFile.transferTo(file);
                    System.out.println("添加图片成功！");
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                }
            }else{
                picName = "";
            }
        }
        return picName;
    }

    //***************--APP--人员进出信息+人数提醒********************//
    public Map<String,Object> getPersonnelRecord(Map<String, Object> paramMap){
        Map<String, Object> res = new HashMap<>();
        List<Map<String,Object>> categoryOneArray = new ArrayList<>();
        paramMap.put("orderType","app");
        paramMap.put("isApp","1");

        paramMap.put("rownum",10);
        List<List<Map<String,Object>>> categoryTwoArrayList = enterExitService.getTop10Enter_ExitList(paramMap);

        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String beginTime = formatter.format(date) + " 00:00:01";
        paramMap.put("beginTime",beginTime);
        List<String> marqueeList = remindService.getAppRemindContent(paramMap);

        List<String> categoryTwoArraySizeList = enterExitService.getEnterExitListCount(paramMap);

        int days = Integer.parseInt(PropertiesUtil.get("PresentDays"));
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance(); //得到日历
        calendar.setTime(new Date());//把当前时间赋给日历
        calendar.add(Calendar.DAY_OF_MONTH, -1*days);  //设置为前一天
        String beginPassTime = sdf1.format(calendar.getTime());
        paramMap.put("beginPassTime",beginPassTime);
        List<String> personnelBePresentCountList = enterExitService.getPresentPersonCount(paramMap);//在场数量

        List<Map<String,Object>> siteList = siteService.getStartedSiteList(paramMap);
        for(int i = 0;i<siteList.size();i++){
            Map<String,Object> siteMap = siteList.get(i);
            Map<String, Object> categoryOneArrayItem = new HashMap<>();
            String siteId = siteMap.get("id")==null?"":siteMap.get("id").toString();
            String siteName = siteMap.get("name")==null?"":siteMap.get("name").toString();
            paramMap.put("siteId",siteId);

            List<Map<String,Object>> categoryTwoArray = categoryTwoArrayList.get(i);
            String tempEnterExitListSize = categoryTwoArraySizeList.get(i);
            if(tempEnterExitListSize.equalsIgnoreCase("0")){
                categoryOneArrayItem.put("categoryTwoArray",new ArrayList<>());
            }else{
                categoryOneArrayItem.put("categoryTwoArray",categoryTwoArray);
            }
            categoryOneArrayItem.put("name",siteName);
            categoryOneArrayItem.put("siteId",siteId);
            categoryOneArrayItem.put("personnelBePresentCount",personnelBePresentCountList.get(i));
            categoryOneArrayItem.put("marquee",marqueeList.get(i));
            categoryOneArrayItem.put("enterExitListSize",tempEnterExitListSize);
            categoryOneArray.add(categoryOneArrayItem);
        }
        res.put("categoryOneArray",categoryOneArray);
        return res;
    }

    //***************--APP--获取基坑监测数据钢琴键布局********************//
    public Map<String,Object> app_getPitList(Map<String, Object> paramMap){
        Map<String, Object> res = new HashMap<>();
        List<Map<String,Object>> categoryOneArray = new ArrayList<>();
        List<Map<String,Object>> pitList = pitService.getInitPitListForApp(paramMap);
        int i;
        List<Map<String,Object>> categoryTwoArray = new ArrayList<>();
        if(pitList != null && pitList.size() > 0){
            String siteId = pitList.get(0).get("SITE_ID").toString();
            for(i = 0; i < pitList.size(); i++){
                Map<String,Object> tempMap = pitList.get(i);
                String siteCompare = tempMap.get("SITE_ID").toString();
                if(siteCompare.equalsIgnoreCase(siteId)){
                    categoryTwoArray.add(tempMap);
                    if (i == pitList.size() - 1) {
                        Map<String, Object> categoryOneArrayItem = new HashMap<>();
                        int listSize = categoryTwoArray.size();
                        if(listSize < 10){
                            categoryOneArrayItem.put("categoryTwoArray",categoryTwoArray.subList(0, listSize));
                        }else{
                            categoryOneArrayItem.put("categoryTwoArray",categoryTwoArray.subList(0, 10));
                        }
                        categoryOneArrayItem.put("siteName",pitList.get(i).get("SITE_NAME"));
                        categoryOneArrayItem.put("siteId",pitList.get(i).get("SITE_ID"));
                        categoryOneArrayItem.put("listCount",listSize);
                        categoryOneArray.add(categoryOneArrayItem);
                    }
                }else{
                    Map<String, Object> categoryOneArrayItem = new HashMap<>();
                    int listSize = categoryTwoArray.size();
                    if(listSize < 10){
                        categoryOneArrayItem.put("categoryTwoArray",categoryTwoArray.subList(0, listSize));
                    }else{
                        categoryOneArrayItem.put("categoryTwoArray",categoryTwoArray.subList(0, 10));
                    }
                    categoryOneArrayItem.put("siteName",pitList.get(i-1).get("SITE_NAME"));
                    categoryOneArrayItem.put("siteId",pitList.get(i-1).get("SITE_ID"));
                    categoryOneArrayItem.put("listCount",listSize);
                    categoryOneArray.add(categoryOneArrayItem);
                    siteId = siteCompare;
                    categoryTwoArray = new ArrayList<>();
                    categoryTwoArray.add(tempMap);
                }
            }
        }
        res.put("categoryOneArray",categoryOneArray);
        return res;
    }

    //***************--APP--获取盾构监测数据钢琴键布局********************//
    public Map<String,Object> app_getTunnelList(Map<String, Object> paramMap){
        Map<String, Object> res = new HashMap<>();
        List<Map<String,Object>> categoryOneArray = new ArrayList<>();
        List<Map<String,Object>> tunnelList = tunnelService.getInitTunnelListForApp(paramMap);
        int i;
        List<Map<String,Object>> categoryTwoArray = new ArrayList<>();
        if(tunnelList != null && tunnelList.size() > 0){
            String bidId = tunnelList.get(0).get("BID_ID").toString();
            for(i = 0; i < tunnelList.size(); i++){
                Map<String,Object> tempMap = tunnelList.get(i);
                String bidCompare = tempMap.get("BID_ID").toString();
                if(bidCompare.equalsIgnoreCase(bidId)){
                    categoryTwoArray.add(tempMap);
                    if (i == tunnelList.size() - 1) {
                        Map<String, Object> categoryOneArrayItem = new HashMap<>();
                        int listSize = categoryTwoArray.size();
                        if(listSize < 10){
                            categoryOneArrayItem.put("categoryTwoArray",categoryTwoArray.subList(0, listSize));
                        }else{
                            categoryOneArrayItem.put("categoryTwoArray",categoryTwoArray.subList(0, 10));
                        }
                        categoryOneArrayItem.put("bidName",tunnelList.get(i).get("BID_NAME"));
                        categoryOneArrayItem.put("bidId",tunnelList.get(i).get("BID_ID"));
                        categoryOneArrayItem.put("listCount",listSize);
                        categoryOneArray.add(categoryOneArrayItem);
                    }
                }else{
                    Map<String, Object> categoryOneArrayItem = new HashMap<>();
                    int listSize = categoryTwoArray.size();
                    if(listSize < 10){
                        categoryOneArrayItem.put("categoryTwoArray",categoryTwoArray.subList(0, listSize));
                    }else{
                        categoryOneArrayItem.put("categoryTwoArray",categoryTwoArray.subList(0, 10));
                    }
                    categoryOneArrayItem.put("bidName",tunnelList.get(i-1).get("BID_NAME"));
                    categoryOneArrayItem.put("bidId",tunnelList.get(i-1).get("BID_ID"));
                    categoryOneArrayItem.put("listCount",listSize);
                    categoryOneArray.add(categoryOneArrayItem);
                    bidId = bidCompare;
                    categoryTwoArray = new ArrayList<>();
                    categoryTwoArray.add(tempMap);
                }
            }
        }
        res.put("categoryOneArray",categoryOneArray);
        return res;
    }

    public void insertPmFile(Map<String, Object> paramsMap,HttpServletRequest request){
        weChatMapper.insertPmFile(paramsMap);
        String picName = this.uploadPic(request);
        Map<String,Object> attachMap = new HashMap<>();
        attachMap.put("parentId",paramsMap.get("id"));
        attachMap.put("name",picName);
        attachMap.put("type","ATTACH_PIC");
        attachMap.put("source","ATTACH_PM");
        if(picName.length() > 0){
            attachService.saveAttach(attachMap);
        }
    }

    public List<Map<String, Object>> getPmFileList(Map<String, Object> paramsMap) {
        List<Map<String,Object>> pmFileList = weChatMapper.getPmFileList(paramsMap);
        return pmFileList;
    }

    public List<Map<String,Object>> getPmFileCount(Map<String, Object> paramsMap){
        return weChatMapper.getPmFileCount(paramsMap);
    }

    public int chkSendNoticePeopleRemind(Map<String, Object> paramsMap) {
        return weChatMapper.chkSendNoticePeopleRemind(paramsMap);
    }


    public void updPeopleRemind(Map<String, Object> paramsMap){
        weChatMapper.updPeopleRemind(paramsMap);
    }

    /*
    获取岗位、站点下拉列表
     */
    public Map<String,Object> app_getWorkTypeAndSite(Map<String, Object> paramsMap){
        paramsMap.put("isApp","1");
        Map<String,Object> res = new HashMap<>();
        List<Map<String,Object>> siteList = siteService.app_getSiteList(paramsMap);
        paramsMap.put("PARENT_CODE","WORK_TYPE");
        List<SysDict> workTypeList = sysDictService.getAllSysDict(paramsMap);
        res.put("siteList",siteList);
        res.put("workTypeList",workTypeList);
        return  res;
    }

     /*
        获取待整改隐患数量；获取待确认隐患数量
     */
     public int appGetHiddenRemindCount(Map<String, Object> params){
         return weChatMapper.appGetHiddenRemindCount(params);
     }

    /*
      获取设备吊装令上传数量
    */
    public int appGetHoistRemindCount(Map<String, Object> params){
        return weChatMapper.appGetHoistRemindCount(params);
    }
}
